package queue

import (
	"errors"
	"fmt"
)

/**
环形队列
注意：需要预留一个空间
*/

type LoopQueue struct {
	MaxSize int
	Array   []int
	Head    int //队首
	Tail    int //队尾
}

func (q *LoopQueue) IsFull() bool {
	return (q.Tail+1)%q.MaxSize == q.Head
}

func (q *LoopQueue) IsEmpty() bool {
	return q.Tail == q.Head
}

func (q *LoopQueue) Size() int {
	return (q.Tail + q.MaxSize - q.Head) % q.MaxSize
}

func (q *LoopQueue) AddLoopQueue(value int) error {
	if q.IsFull() {
		return errors.New("队列已满！")
	}
	q.Array[q.Tail] = value
	q.Tail = (q.Tail +1) % q.MaxSize
	return nil
}

func (q *LoopQueue) ShowLoopQueue() {
	if q.IsEmpty() {
		fmt.Println("队列为空！")
		return
	}
	temp := q.Head
	for i := 0; i < q.Size(); i++ {
		fmt.Printf("Array[%d] = %d\n", temp, q.Array[temp])
		temp = (temp + 1) % q.MaxSize
	}
}

func (q *LoopQueue) GetLoopQueue() (interface{}, error) {
	if q.IsEmpty() {
		return nil, errors.New("队列为空！~")
	}
	val := q.Array[q.Head]
	q.Head = (q.Head  +1) % q.MaxSize
	return val, nil
}
